package com.baoyouqun.API.sms;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baoyouqun.API.IM.ImConfig;
import com.baoyouqun.API.IM.TencentImService;
import com.baoyouqun.base.BusinessException;
import com.baoyouqun.entity.City;
import com.baoyouqun.entity.User;
import com.baoyouqun.entity.UserVipTime;
import com.baoyouqun.entity.WechatPushRecord;
import com.baoyouqun.mapper.CityMapper;
import com.baoyouqun.service.UserService;
import com.baoyouqun.service.UserVipTimeService;
import com.baoyouqun.service.WechatPushService;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.apache.poi.util.StringUtil;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/sms/batch")
@SaIgnore
public class SmsBatchController {

    @Resource
    private SmsBatchService smsBatchService;
    @Resource
    private UserService userService;
    @Resource
    private UserVipTimeService userVipTimeService;
    @Resource
    private CityMapper cityMapper;
    @Resource
    private WechatPushService wechatPushService;
    @Resource
    private ImConfig imConfig;
    @Resource
    private TencentImService tencentImService;

    /**
     * 批量发送系统消息
     *
     * @param receiverUserIds 接收者用户ID列表
     * @param messageVO       消息内容
     */
    @PostMapping("/im/sendBatchSystemMsg")
    public Response sendBatchSystemMessage(
            @RequestParam List<String> receiverUserIds,
            @RequestBody WechatPushRecord messageVO) {
        try {
            // 使用管理员账号作为发送者
            String adminUserId = imConfig.getAdminUserId();
            tencentImService.sendBatchMessage(adminUserId, receiverUserIds, messageVO);
            return Response.buildSuccess();
        } catch (BusinessException e) {
            return Response.buildFailure("100312", e.getMessage());
        } catch (Exception e) {
            return Response.buildFailure("100407", "批量发送消息异常：" + e.getMessage());
        }
    }

    /**
     * 批量发送模板短信接口
     */
    @ApiOperation("批量发送模板短信")
    @PostMapping("/batch/send")
    public SingleResponse batchSend(@Valid @RequestBody BatchSmsSendDTO dto) {
        // 1. 获取符合条件的用户ID列表
        List<User> userList = getUserIdsByFilter(dto);
        List<String> userIds = userList.stream().map(User::getId).collect(Collectors.toList());
        List<String> cellphoneList = userList.stream().map(User::getCellphone).collect(Collectors.toList());
        List<String> imUserIds = userList.stream().map(User::getImUserSig).filter(StringUtil::isNotBlank).collect(Collectors.toList());

        cellphoneList = List.of("15779060760", "13507094220", "13576044283");
        userIds = List.of("1", "1979520546709487617", "000bd6549abe44be9d3d03fa996594e9");

        if (CollUtil.isEmpty(userIds)) {
            throw new RuntimeException("没有符合条件的推送用户");
        }


        // 2. 保存推送记录
        WechatPushRecord record = new WechatPushRecord();
        record.setTitle(dto.getTitle());
        record.setContent(dto.getContent());
        record.setFilterConditions(JSON.toJSONString(dto));
        record.setPushTime(LocalDateTime.now());
        record.setStatus(1); // 假设立即推送
        record.setUserCount(userIds.size());
        record.setCreateBy(StpUtil.getLoginIdAsString());
        record.setCreateTime(LocalDateTime.now());
        wechatPushService.save(record);

        if (StringUtil.isNotBlank(dto.getTemplateCode())) {
            smsBatchService.batchSendTemplateSms(
                    cellphoneList,
                    dto.getTemplateCode(),
                    new ArrayList<>(),
                    StpUtil.getLoginIdAsString()
            );
        } else {
            // 使用管理员账号作为发送者（系统消息推荐）
            String adminUserId = imConfig.getAdminUserId();
            tencentImService.sendBatchMessage(adminUserId, imUserIds, record);
        }

        return SingleResponse.buildSuccess();
    }


    /**
     * 根据筛选条件获取用户ID列表
     */
    public List<User> getUserIdsByFilter(BatchSmsSendDTO dto) {
        // 1. 基础查询条件
        List<User> users = userService.list(Wrappers.<User>lambdaQuery()
                .select(User::getId, User::getCellphone)
                .eq(User::getDisEnable, false)
                .eq(User::getLogout, false)
                .eq(dto.getBaoZhiHao() != null, User::getBaoZhiHao, dto.getBaoZhiHao()) // 假设存在baoZhiHao字段
                .eq(StringUtil.isNotBlank(dto.getSex()), User::getSex, dto.getSex())
                .in(CollUtil.isNotEmpty(dto.getIndustryList()), User::getIndustry, dto.getIndustryList()));

        if (CollUtil.isEmpty(users)) {
            return new ArrayList<>();
        }

        List<String> userIds = users.stream().filter(Objects::nonNull).map(User::getId).filter(StringUtil::isNotBlank).distinct().collect(Collectors.toList());

        // 2. 会员筛选
        if (dto.getIsVip() != null) {
            Set<String> vipUserIds = userVipTimeService.list(Wrappers.<UserVipTime>lambdaQuery()
                            .gt(UserVipTime::getEndTime, LocalDateTime.now())
                            .in(UserVipTime::getUserId, userIds))
                    .stream()
                    .map(UserVipTime::getUserId)
                    .collect(Collectors.toSet());

            userIds = userIds.stream()
                    .filter(id -> dto.getIsVip() == vipUserIds.contains(id))
                    .collect(Collectors.toList());
        }

        // 3. 地区筛选（包含下级城市）
        if (StringUtil.isNotBlank(dto.getCityCode())) {
            List<String> allCityCodes = getAllSubCityCodes(dto.getCityCode());
            allCityCodes.add(dto.getCityCode()); // 包含自身

            userIds = userService.listObjs(Wrappers.<User>lambdaQuery()
                    .select(User::getId, User::getCellphone)
                    .in(User::getCityCode, allCityCodes)
                    .in(CollUtil.isNotEmpty(userIds), User::getId, userIds));
        } else {
            dto.setCityCode("全国");
        }

        return users;
    }

    /**
     * 递归获取所有下级城市编码
     */
    private List<String> getAllSubCityCodes(String parentCode) {
        List<City> childCities = cityMapper.selectList(Wrappers.<City>lambdaQuery()
                .eq(City::getParentCode, parentCode));

        if (CollUtil.isEmpty(childCities)) {
            return new ArrayList<>();
        }

        List<String> result = new ArrayList<>();
        for (City city : childCities) {
            result.add(city.getCode());
            result.addAll(getAllSubCityCodes(city.getCode())); // 递归获取下级
        }
        return result;
    }
}